import { createApp, nextTick } from 'vue';
import { Quasar } from 'quasar';
import MediaPicker from '@/views/media-picker/index.vue';

// 定义选择结果的类型
interface MediaResult {
  id: string;
  url: string;
}

// 定义组件实例类型
interface MediaPickerInstance {
  show: () => void;
  hide: () => void;
}

export const useMenu = () => {
  const selectMedia = (id: string, type: string): Promise<MediaResult> => {
    return new Promise((resolve, reject) => {
      // 创建临时容器
      const container = document.createElement('div');
      document.body.appendChild(container);

      // 创建 Vue 应用实例
      const app = createApp(MediaPicker, {
        id,
        type,
        resolve: (result: MediaResult) => {
          cleanup();
          resolve(result);
        },
        reject: (error?: any) => {
          cleanup();
          reject(error || new Error('用户取消选择'));
        }
      });

      // 配置 Quasar（确保动态组件能正常使用 Quasar 组件）
      app.use(Quasar, {
        plugins: {}
      });

      // 挂载组件
      const instance = app.mount(container) as unknown as MediaPickerInstance;

      // 清理函数
      const cleanup = () => {
        try {
          app.unmount();
          if (document.body.contains(container)) {
            document.body.removeChild(container);
          }
        } catch (error) {
          console.warn('清理组件时出错:', error);
        }
      };

      // 自动显示弹窗
      // 使用 nextTick 确保组件完全挂载后再调用 show
      nextTick(() => {
        if (instance && typeof instance.show === 'function') {
          instance.show();
        }
      });

      // 添加错误处理
      app.config.errorHandler = (error) => {
        console.error('MediaPicker 组件错误:', error);
        cleanup();
        reject(new Error('组件运行时错误'));
      };
    });
  };

  return {
    selectMedia,
  };
};
